import 'dart:collection';
import 'dart:ui';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/common_language_dao.dart';
import 'package:changxindianzishangwu/model/common_language_model.dart';
import 'package:changxindianzishangwu/pages/my/settings/common_language_add_page.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/common_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';

class CommonLanguagePage extends StatefulWidget {
  int type;

  ///1打招呼 2自动回复 3常用语 额外的接口
  CommonLanguagePage(this.type);

  @override
  _CommonLanguagePageState createState() => _CommonLanguagePageState();
}

class _CommonLanguagePageState extends State<CommonLanguagePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  String resultString = "";

  @override
// TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  List<CommonLanguageBean> _lists = [];

  bool isLoading = true;

  getDataList() async {
    print('userId:${getUserInfo().userId}');
    _lists.clear();
    LinkedHashMap hashMap = await CommonLanguageDao.getData(widget.type);
    isLoading = false;

    if (!hashMap.containsKey("data")) {
      setState(() {
      });
      return;
    }
    CommonLanguageModel commonLanguageModel =
        CommonLanguageModel.fromJson(hashMap);

    if (commonLanguageModel.resultCode != 1) {
      return;
    }

    if (widget.type==2&&commonLanguageModel.data.length > 0) {
      setAutoReply(commonLanguageModel.data[0].context);
    }

    if (mounted)
      setState(() {
        _lists.addAll(commonLanguageModel.data);
      });
  }

  @override
  void initState() {
    super.initState();
    getDataList();
  }

  @override
  Widget build(BuildContext context) {
    print('token:${getAppLoginToken()}');

    return Scaffold(
      backgroundColor: Color(0xfff2f2f2),
      appBar: TopAppBar(
        context,
        widget.type == 1
            ? "打招呼内容"
            : widget.type == 2
                ? "自动回复内容"
                : "常用语",
        rightWidget: (widget.type == 1 && _lists.length < 5) ||
                (widget.type == 2 && _lists.length < 1) ||
                widget.type == 3
            ? Icon(
                Icons.add_circle_outline,
                color: AppColor.colorDefaultText,
                size: 18,
              )
            : null,
        rightCallback: () {
          Get.to(CommonLanguageAddPage("", "", widget.type)).then((value) {
            value.isEmpty ? null : getDataList();
          });
        },
      ),
      body: Container(
        color: Colors.white,
        child: CustomScrollView(
          slivers: [_sliverList()],
        ),
      ),
    );
  }

  Widget _sliverList() {
    return isLoading
        ? SliverToBoxAdapter(
            child: CommonPage.loading(() {
              getDataList();
            }),
          )
        : SliverList(
            delegate:
                SliverChildBuilderDelegate((BuildContext content, int index) {
              return _sliverItem(index);
            }, childCount: _lists.length),
          );
  }

  Widget _sliverItem(int index) {
    CommonLanguageBean bean = _lists[index];

    return Container(
      height: 60,
      child: Column(
        children: [
          Container(
            height: 56,
            child: Slidable(
                actionPane: SlidableScrollActionPane(),
                //滑出选项的面板 动画
                actionExtentRatio: 0.25,
                closeOnScroll: true,
                secondaryActions: <Widget>[
                  IconSlideAction(
                      caption: '删除',
                      color: Colors.red,
                      icon: Icons.delete,
                      closeOnTap: true,
                      onTap: () async {
                        _delete(
                            index, widget.type == 3 ? bean.cwordsId : bean.id);
                      }),
                ],
                child: InkWell(
                  onTap: () {
                    print('${bean.id}');
                    Get.to(CommonLanguageAddPage(
                            bean.context,
                            widget.type == 3 ? bean.cwordsId : bean.id,
                            widget.type))
                        .then((value) => value.isEmpty ? null : getDataList());
                  },
                  child: Container(
                      alignment: Alignment.centerLeft,
                      margin: EdgeInsets.only(
                        left: 15,
                        right: 15,
                      ),
                      child: Text(bean.context ?? "",
                          style: TextStyle(fontSize: sp(15)))),
                )),
          ),
          UniversalView().line()
        ],
      ),
    );
  }

  ///删除自动回复
  void _delete(index, id) async {
    EasyLoading.show();
    var hashMap = await CommonLanguageDao.deleteData(widget.type, id);
    EasyLoading.dismiss();
    if (hashMap["resultCode"] == 1) {
      setState(() {
        _lists.removeAt(index);
      });
    } else {
      toast(hashMap["resultMsg"]);
    }
  }

  @override
  void dispose() {
    EasyLoading.dismiss();

    // TODO: implement dispose
    super.dispose();
  }
}
